package com.lxf.cloudotherserve.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.lxf.cloudfeign.client.userClient.UserClient;
import com.lxf.cloudotherserve.bean.UserCommentBean;
import com.lxf.cloudotherserve.mapper.UserCommentItemRepository;
import com.lxf.cloudotherserve.mapper.UserCommentMapper;
import com.lxf.cloudotherserve.service.BaseStrategy;
import com.lxf.cloudotherserve.service.UserCommentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author 罗兴发
 * @data 2025/6/30 10:51
 * @description：用户评论-业务实现类
 */
@Slf4j
@Service
public class UserCommentServiceImpl implements UserCommentService {

    @Resource
    UserCommentMapper userCommentMapper;
    @Resource
    private UserClient userClient;
    @Resource
    private UserCommentItemRepository userCommentItemRepository;

    @Resource
    private Map<String, BaseStrategy> baseStrategyMap;

    /**
     * 添加评论
     * @param json
     * @param request
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String addUserComment(JSONObject json, HttpServletRequest request) {
        JSONObject js = new JSONObject();
        //获取请求凭证,凭证中存放用户ID和用户名，存放格式为：userId_userName
        String secretToken = request.getHeader("secretToken");

        JSONObject j1 = new JSONObject();
        j1.put("redis_key",secretToken);
        //获取redis中缓存的token
        String o = userClient.getRedisData(j1);
        if (null!=o) {
            //截取请求头中存储的用户ID
            int secretTokenIndex = secretToken.lastIndexOf(":");
            String userIdSub = secretToken.substring(secretTokenIndex + 1);
            Integer userId = Integer.valueOf(userIdSub);//用户ID
            try {
                //前端参数
                Integer type = json.getInteger("obj_type");//对象类型：0商品 其他待定
                Integer pId = json.getInteger("p_id");//父级评论ID
                Integer pUserId = json.getInteger("p_user_id");//父级评论的用户ID
                String objId = json.getString("obj_id");//评论的对象ID，例如：商品编码，视频ID
                String content = json.getString("content");//评论内容

                //根据用户ID查询评论者信息
                // 根据用户ID查询用户信息
                JSONObject js1 = new JSONObject();
                js1.put("user_id",userId);

                //根据用户ID查询评论者信息
                String u = userClient.findById(js1);
                JSONObject j2 = JSONObject.parseObject(u);
                String data = j2.getString("data");

                //实体数据返回
                JSONObject j3 = JSONObject.parseObject(data);

                String userName = j3.getString("userName");
                String userHead = j3.getString("userHead");

                //时间规格化
                SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String addTime = sf.format(new Date());

                //对象实例化
                UserCommentBean uc = new UserCommentBean();
                uc.setUserId(userId);
                uc.setPUserId(pUserId);
                if (pUserId!=0){
                    //根据用户ID查询被回复者的信息
                    js1.put("user_id",userId);

                    //根据用户ID查询评论者信息
                    String u2 = userClient.findById(js1);
                    JSONObject j4 = JSONObject.parseObject(u2);
                    String data1 = j4.getString("data");

                    //实体数据返回
                    JSONObject j5 = JSONObject.parseObject(data1);

                    String pUserName = j5.getString("userName");
                    String pUserHead = j5.getString("userHead");
                    uc.setPUserName(pUserName);
                    uc.setPUserHead(pUserHead);
                }
                uc.setUserName(userName);
                uc.setUserHead(userHead);
                uc.setObjType(type);
                uc.setPId(pId);
                uc.setObjId(objId);
                uc.setUcContent(content);
                uc.setAddTime(addTime);

                //list封装
                List<UserCommentBean> list = new ArrayList<>();
                list.add(uc);

                //添加操作
                int flag = userCommentMapper.addUserComment(list);
                if (flag<0){
                    js.put("code",401);
                    js.put("msg","Fails");
                }else {
                    js.put("code",200);
                    js.put("msg","Success");

                    //将用户ID封装到请求参数中，以便直接查询数据
                    json.put("user_id",userId);
                    //获取打分数据
                    int userRating = userClient.getUserRatingById(json);

                    //将分数加一
                    userRating = userRating+1;
                    json.put("user_rating",userRating);

                    //用户打分操作
                    userClient.addUserRating(json);

                    //es存储
                    userCommentItemRepository.save(uc);

                    //根据类型获取相应信息
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("obj_type",type);

                    String d = userClient.getDataNameAndDesc(jsonObject);
                    JSONObject j4 = JSONObject.parseObject(d);

                    String name = j4.getString("name");

                    //根据类型，获取相应信息
                    BaseStrategy baseStrategy = baseStrategyMap.get(name);
                    Map infos = baseStrategy.getInfos(objId,null);
                    String objTitle = String.valueOf(infos.get("objTitle"));
                    String proUserId = String.valueOf(infos.get("userId"));
                    String cover = String.valueOf(infos.get("cover"));

                    //消息参数封装
                    JSONObject j = new JSONObject();
                    if (pUserId==0){
                        //详细信息
                        String contentInfo = "<div><p id='objId'>"+objId+"</p><p id='objType'>"+type+"</p><p id='objTitle'>"+objTitle+"</p><p id='cover'><img src='"+cover+"'></p></div>";
                        String usersInfo = "<div><p id='userId'>"+userId+"</p><p id='userName'>"+userName+"</p><p id='userHead'>"+userHead+"</p></div>";
                        String commentInfo = "<div><p id='commentId'>"+uc.getUcId()+"</p><p id='contents'>评论："+content+"</p></div>";

                        //最终发送消息
                        String msg = contentInfo+usersInfo+commentInfo;

                        //给发布者发送消息通知
                        j.put("user_id",proUserId);
                        j.put("msg",msg);
                    }else {
                        //详细信息
                        String contentInfo = "<div><p id='objId'>"+objId+"</p><p id='objType'>"+type+"</p><p id='objTitle'>"+objTitle+"</p><p id='cover'><img src='"+cover+"'></p></div>";
                        String usersInfo = "<div><p id='userId'>"+userId+"</p><p id='userName'>"+userName+"</p><p id='userHead'>"+userHead+"</p></div>";
                        String commentInfo = "<div><p id='commentId'>"+uc.getUcId()+"</p><p id='contents'>回复："+content+"</p></div>";

                        //最终发送消息
                        String msg = contentInfo+usersInfo+commentInfo;

                        //给上级评论者发送消息通知
                        j.put("user_id",String.valueOf(pUserId));
                        j.put("msg",msg);
                    }

                    //发送消息
                    userClient.sendPrivateMsg(j);
                }
            }catch (Exception e){
                js.put("code",500);
                js.put("msg",e.getMessage());
            }
        }else {
            js.put("code",400);
            js.put("msg","The Current Request is Invalid");
        }

        return JSONObject.toJSONString(js, SerializerFeature.WriteMapNullValue);
    }

    /**
     * 获取评论
     * @param json
     * @return
     */
    @Override
    public String getUserComment(JSONObject json) {
        JSONObject js = new JSONObject();

        // 前端参数
        Integer type = json.getInteger("obj_type");//对象类型：0商品 其他待定
        String objId = json.getString("obj_id");//对象ID，如：商品编码
        Integer page = json.getInteger("page");
        Integer size = json.getInteger("size");

        //初始页
        Integer starPage = (page - 1) * size;

        //查询结果
        Page<UserCommentBean> comments = userCommentItemRepository.findAllByObjIdAndObjType(type, objId, PageRequest.of(starPage, size));
        js.put("code",200);
        js.put("msg","Success");
        js.put("data",comments);

        return JSONObject.toJSONString(js, SerializerFeature.WriteMapNullValue);
    }

    /**
     * 删除评论
     * @param json
     * @param request
     * @return
     */
    @Override
    public String delUserCommentById(JSONObject json, HttpServletRequest request) {
        JSONObject js = new JSONObject();
        //获取请求凭证,凭证中存放用户ID和用户名，存放格式为：userId_userName
        String secretToken = request.getHeader("secretToken");

        JSONObject j1 = new JSONObject();
        j1.put("redis_key",secretToken);
        //获取redis中缓存的token
        String o = userClient.getRedisData(j1);
        if (null!=o) {
            //截取请求头中存储的用户ID
            int secretTokenIndex = secretToken.lastIndexOf(":");
            String userIdSub = secretToken.substring(secretTokenIndex + 1);
            Integer userId = Integer.valueOf(userIdSub);//用户ID
            try {
                //前端参数
                String commentId = json.getString("comment_id");//评论ID

                //根据评论查询信息
                UserCommentBean comment = userCommentItemRepository.findById(commentId).get();
                Integer comUserId = comment.getUserId();//评论者ID
                String objId = comment.getObjId(); //对象ID
                Integer type = comment.getObjType(); //对象类型

                //根据类型获取相应信息
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("obj_type",type);

                String d = userClient.getDataNameAndDesc(jsonObject);
                JSONObject j4 = JSONObject.parseObject(d);

                String name = j4.getString("name");

                //根据类型，获取相应信息
                BaseStrategy baseStrategy = baseStrategyMap.get(name);
                Map infos = baseStrategy.getInfos(objId,null);
                String proUserId = String.valueOf(infos.get("userId"));//发布者用户ID

                // 仅有当前内容发布者或者当前评论发布者才可删除此评论
                if (userId==comUserId||userId==Integer.valueOf(proUserId)){

                    //mysql删除
                    userCommentMapper.deleteById(commentId);

                    //es删除
                    userCommentItemRepository.deleteById(commentId);
                }

                js.put("code",200);
                js.put("msg","Success");
            }catch (Exception e){
                js.put("code",500);
                js.put("msg",e.getMessage());
            }
        }else {
            js.put("code",400);
            js.put("msg","The Current Request is Invalid");
        }

        return JSONObject.toJSONString(js, SerializerFeature.WriteMapNullValue);
    }

    @Override
    public int delESUserComment() {
        userCommentItemRepository.deleteAll();
        return 1;
    }
}
